struct Solution;

impl Solution {
    pub fn longest_ones(a: Vec<i32>, k: i32) -> i32 {
        let mut k = k;
        let mut start = 0;
        let mut end = 0;
        let mut max = 0;

        for (index, val) in a.iter().enumerate() {
            start = index;
            if *val == 0 {
                k -= 1;
                if k < 0 {
                    // 移动end指针前，计算目前能拥有的长度
                    if start - end > max {
                        max = start - end;
                    }
                    for (pre_index, pre) in a[end..=index].iter().enumerate() {
                        if *pre == 0 {
                            k += 1;
                            // 这里在最后的时候可能会过界，需要做下限制
                            end = end + pre_index + 1;
                            break;
                        }
                    }
                }
            }
        }

        if end < a.len() && start - end + 1 > max {
            max = start - end + 1;
        }

        max as i32
    }
}


#[cfg(test)]
mod test {
    use crate::Solution;

    #[test]
    fn test_01() {
        let a = vec![1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0];
        let k = 2;
        let res = Solution::longest_ones(a, k);
        assert_eq!(res, 6);
    }

    #[test]
    fn test_02() {
        let a = vec![0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1];
        let k = 3;
        let res = Solution::longest_ones(a, k);
        assert_eq!(res, 10);
    }

    #[test]
    fn test_03() {
        let a = vec![0, 0, 0, 0];
        let k = 0;
        let res = Solution::longest_ones(a, k);
        assert_eq!(res, 0);
    }

    #[test]
    fn test_04() {
        let a = vec![1, 1, 1, 1];
        let k = 0;
        let res = Solution::longest_ones(a, k);
        assert_eq!(res, 4);
    }
}

fn main() {
    let a = vec![1, 1, 1, 1];
    let k = 0;
    let res = Solution::longest_ones(a, k);
    assert_eq!(res, 4);
}
